﻿Public Class ImageExt
    ''' <summary>
    ''' Converts an image into an icon.
    ''' </summary>
    ''' <param name="img">The image that shall become an icon</param>
    ''' <param name="size">The width and height of the icon. Standard
    ''' sizes are 16x16, 32x32, 48x48, 64x64.</param>
    ''' <param name="keepAspectRatio">Whether the image should be squashed into a
    ''' square or whether whitespace should be put around it.</param>
    ''' <returns>An icon!!</returns>
    Public Shared Function ToIcon(img As System.Drawing.Image, size As Integer, keepAspectRatio As Boolean) As System.Drawing.Icon

        Dim square As New System.Drawing.Bitmap(size, size)
        ' create new bitmap
        Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(square)
        ' allow drawing to it
        Dim x As Integer, y As Integer, w As Integer, h As Integer

        If img Is Nothing Then
            Return Nothing
        End If

        ' dimensions for new image
        If Not keepAspectRatio OrElse img.Height = img.Width Then
            ' just fill the square
            x = 0
            y = 0
            ' set x and y to 0
            ' set width and height to size
            w = size
            h = size
        Else
            ' work out the aspect ratio
            Dim r As Single = CSng(img.Width) / CSng(img.Height)

            ' set dimensions accordingly to fit inside size^2 square
            If r > 1 Then
                ' w is bigger, so divide h by r
                w = size
                h = CInt(Math.Truncate(CSng(size) / r))
                x = 0
                ' center the image
                y = (size - h) \ 2
            Else
                ' h is bigger, so multiply w by r
                w = CInt(Math.Truncate(CSng(size) * r))
                h = size
                y = 0
                ' center the image
                x = (size - w) \ 2
            End If
        End If

        ' make the image shrink nicely by using HighQualityBicubic mode
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
        g.DrawImage(img, x, y, w, h)
        ' draw image with specified dimensions
        g.Flush()
        ' make sure all drawing operations complete before we get the icon
        ' following line would work directly on any image, but then
        ' it wouldn't look as nice.
        Return System.Drawing.Icon.FromHandle(square.GetHicon())
    End Function

End Class
